﻿using System;
//using CommunityServer.Groups;
//using CommunityServer.Membership;
//using CommunityServer.WebServices.Common;
using NENAData.Errors;
using NENAData.LINQ;
using NENAData.Transactions.Payments.Cheque;
using NENAData.Transactions.Payments.Other;
using PerceptiveMCAPI;
using PerceptiveMCAPI.Types;
using PerceptiveMCAPI.Methods;
using System.Collections.Generic;

namespace NENAData.NENAMember.Account
{
    public class Activate
    {

        public void MembershipAccount(int intAffiliateId, int intMemberId, bool boolPayMember, Payments.NENAPayments.PaidBy oPaidBy, int intTransactionPaymentId)
        {


            try
            {
                string strTransactionPaymentId = "";

                //1) update member paid on their profile
                NENAMember oNENAMember = new NENAMember();
                if (boolPayMember)
                {
                    oNENAMember.UpdateMemberApplication(intMemberId, MemberStatus.Status.Paid);
                }
                //2) Create transaction record
                switch (oPaidBy)
                {
                    case Payments.NENAPayments.PaidBy.PayPal:
                        //paypal is processed in the local procedure because of function requirements
                        //PayPal.OrderConfirmation
                        strTransactionPaymentId = intTransactionPaymentId.ToString();
                        break;
                    case Payments.NENAPayments.PaidBy.Cheque:
                        ChequeTransactions oPayment = new ChequeTransactions();
                        strTransactionPaymentId = oPayment.NewPayment(intMemberId, intAffiliateId, Transactions.TransactionList.Transactions.Membership2012);
                        break;
                }
                //3) send transaction receipt email
                Email.Message.PaymentCompleted(intMemberId, strTransactionPaymentId, intAffiliateId);

                //4) Check if the user exists
                //a) check member record for a PNUID
                Member oMember = oNENAMember.GetMember(intMemberId);

                if (oMember.CS_UserName == "")
                {
                    //no account exists
                    //i) check if another account has the same username
                    string strAccountName = oMember.LastName + oMember.FirstName;
                    strAccountName = strAccountName.Replace(" ", "");
                    NENAMember oNenaMember = new NENAMember();
                    bool boolUniqueUserName = oNenaMember.UniqueCsUserName(strAccountName);
                    if (!boolUniqueUserName)
                    {
                        //duplicate account
                        Email.Message.DuplicateAccount(intMemberId, intAffiliateId);
                        return;
                    }
                    //insert a new account
                    //Email the member with account information
                    //updates the member object with CS information
                    oNenaMember.CreateTelligentCommunityUser(oMember.Member_ID);
                    //update the member object
                    oMember = oNENAMember.GetMember(intMemberId);
                    //put the member in the current_member role
                    //AssignCurrentMember(strAccountName);
                    //todo: consider moving assign member/group outside of individual if clauses
                    AssignTcCurrentMember(oMember.CS_UserID);
                    //todo: readd assigngroups
                    //assign group membership to the member
                    //AssignGroups(strAccountName, oMember.Affiliate_ID);
                }
                else
                {
                    //activate account
                    AssignTcCurrentMember(oMember.CS_UserID);
                    //assign group membership to the member
                    //todo: readd assigngroups
                    //AssignGroups(oMember.CS_UserName, oMember.Affiliate_ID);
                    Email.Message.ActivatedAccount(oMember);
                }
                CreateMailChimpAccount(oMember);
                // All paid members get a referral code created
                Referral.Generate oReferral = new Referral.Generate();
                oReferral.GenerateUnqiueMemberReferralCode(intMemberId);
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError("Failed Processing account : " + intMemberId + "\r\n Error: " + ex.Message);
                throw;
            }
        }


        public static void CreateMailChimpAccount(Member mem)
        {

            // input parameters, using default apikey
            listsInput input = new listsInput(MCAPISettings.default_apikey);
            // execution
            lists cmd = new lists(input);
            listsOutput output = cmd.Execute();
            // format output (Assuming a User control named show_lists)
            //show_lists1.Display(output);


            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("FNAME", mem.FirstName);
            dic.Add("LNAME", mem.LastName);
            dic.Add("PROVINCE", mem.Province);

            listSubscribeInput lip = new listSubscribeInput(output.result[0].id, mem.EmailAddress, dic, EnumValues.emailType.html, true, true, true, false);
            listSubscribe lst = new listSubscribe(lip);
            listSubscribeOutput lso = lst.Execute();


        }

        /// <summary>
        /// BROKEN: Use MemberId instead
        /// </summary>
        /// <param name="strAccountName"></param>
        /*
        public static void AssignCurrentMember(string strAccountName)
        {
            APIUser oApiUser = new APIUser();
            oApiUser.AddUsertoRole(strAccountName, Roles.Current_Member );
        }
         */
        //public static void AssignCurrentMember(int intMemberId)
        //{
        //    APIUser oApiUser = new APIUser();
        //    oApiUser.AddUsertoRole(intMemberId, Roles.Current_Member);
        //}
        public static void AssignTcCurrentMember(int TcMemberId)
        {
            NENAData.NENAMember.TcMembership tcMembership = new TcMembership();
            tcMembership.AddUserToRole(TcMemberId, TelligentCommunity.Roles.Current_Member);
        }

        /*
        private static void AssignGroups(string strAccountName, int intAffiliateId)
        {
            try
            {
                APIUser oApiUser = new APIUser(); 
                Groups oApiGroup = new Groups();
                int intUserId = oApiUser.GetUserId(strAccountName);
                //add affiliate if supported
                switch (intAffiliateId)
                {
                    case 1:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.ENABC, intUserId, MembershipType.Member);
                        break;
                    case 2:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.ENIG, intUserId, MembershipType.Member);
                        break;
                    case 3:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.SENG, intUserId, MembershipType.Member);
                        break;
                    case 4:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.EDNA, intUserId, MembershipType.Member);
                        break;
                    case 5:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.ENAO, intUserId, MembershipType.Member);
                        break;
                    case 6:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.NBENA, intUserId, MembershipType.Member);
                        break;
                    case 7:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.NSENA, intUserId, MembershipType.Member);
                        break;
                    case 8:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.PEIENA, intUserId, MembershipType.Member);
                        break;
                    case 9:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.NLENA, intUserId, MembershipType.Member);
                        break;
                    case 10:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.International, intUserId, MembershipType.Member);
                        break;
                    case 11:
                        oApiGroup.AddMembertoGroup(NENAAffiliates.Independant, intUserId, MembershipType.Member);
                        break;
                }
            }
	        catch (Exception ex)
		        {
                    ErrHandler.WriteError("Failed Adding Group; Affiliate ID : " + intAffiliateId + "Account: " + strAccountName + 
                        "\r\n Error: " + ex.Message);
		        }
            }
         */

        /*
        public void RebuildMembershipAccount(int intAffiliateId, int intMemberId, bool boolPayMember)
        {
            try
            {
                //1) update member paid on their profile
                NENAMember oNENAMember = new NENAMember();
                if (boolPayMember)
                {
                    oNENAMember.UpdateMemberApplication(intMemberId, MemberStatus.Status.Paid);
                }
                //2) Create transaction record
                    //case Payments.NENAPayments.PaidBy.Unknown:
                OtherTransactions oPayment = new OtherTransactions();
                        oPayment.NewPayment(intMemberId, intAffiliateId, Transactions.TransactionList.Transactions.Membership2012);
                //3) Check if the user exists
                //a) check member record for a PNUID
                Member oMember = oNENAMember.GetMember(intMemberId);
                if (oMember.CS_UserID  == 0)
                {
                    //no account exists
                    //i) check if another account has the same username
                    string strAccountName = oMember.LastName + oMember.FirstName;
                    strAccountName = strAccountName.Replace(" ", "");
                    NENAMember oNenaMember = new NENAMember();
                    bool boolUniqueUserName = oNenaMember.UniqueCsUserName(strAccountName);
                    if (!boolUniqueUserName)
                    {
                        //duplicate account
                        Email.Message.DuplicateAccount(intMemberId, intAffiliateId);
                        return;
                    }
                    //insert a new account
                    //Email the member with account information
                    oNenaMember.CreateTelligentCommunityUser(oMember.Member_ID);
                    //assign group membership to the member
                    oMember = oNENAMember.GetMember(intMemberId);
                    //put the member in the current_member role
                    //AssignCurrentMember(strAccountName);
                    AssignTcCurrentMember(oMember.CS_UserID);
                    //assign group membership to the member
                    AssignGroups(strAccountName, oMember.Affiliate_ID);
                }
                else
                {
                    //activate account
                    AssignTcCurrentMember(oMember.CS_UserID);
                    //assign group membership to the member
                    AssignGroups(oMember.CS_UserName, oMember.Affiliate_ID);
                }
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError("Failed Processing account : " + intMemberId + "\r\n Error: " + ex.Message);
                throw;
            }
        }
         */
    }
}
